Javascript find()和filter()的区别用法及代码示例

您所在的位置:网站首页 find与find out的区别 Javascript find()和filter()的区别用法及代码示例

Javascript find()和filter()的区别用法及代码示例

2024-07-10 02:45| 来源: 网络整理| 查看: 265

在本文中,我们将了解 JavaScript 中 find() 和 filter() 方法之间的区别。

JavaScript find() 方法: Array.find()用于查找所选元素的所有后代元素。它通过遍历根到叶子来查找 DOM 树中的元素。

用法:

array.find(function(currentValue, index, arr),thisValue);

示例 1:此示例使用find()方法来搜索元素。

HTML                           $(document).ready(function() {             $("ul").find(":odd")             .css("background-color", "yellow");         });                             GeeksForGeeks                 Find() Method                     GeeksforGeeks1.         GeeksforGeeks2.                      GeeksforGeeks3.             GeeksforGeeks4.                              GeeksforGeeks5.                 GeeksforGeeks6.                           

输出:

What is the difference between find() and filter() methods in JavaScript ?

JavaScript filter() 方法: Array filter()用于过滤所有元素,返回匹配的元素,不匹配的元素被移除。唯一的区别是filter()方法搜索所有元素,同时find()方法仅搜索所有子元素。

用法:

array.filter(callback(element, index, arr), thisValue)

示例 2:当我们使用filter()方法进行搜索时所做的更改。

HTML                           $(document).ready(function() {             $("ul").filter(":odd").                 css("background-color", "yellow");         });                         GeeksForGeeks                 Find() Method                 GeeksforGeeks1.         GeeksforGeeks2.                      GeeksforGeeks3.             GeeksforGeeks4.                              GeeksforGeeks5.                 GeeksforGeeks6.                           

输出:

What is the difference between find() and filter() methods in JavaScript ?

让我们看看表格形式的差异:

find()

filter()

1. find()方法用于查找所选元素的所有后代元素。 filter()方法用于过滤所有元素 2. find() 方法通过遍历根到叶子来查找 DOM 树中的元素。 filter()方法返回匹配的元素并删除不匹配的元素。 3. find() 方法仅搜索所有子元素。 filter() 方法搜索所有元素 4. 它不会对空元素执行该函数。 filter()方法不会更改原始数组。 5. 它不会改变原始数组。 filter() 方法不会对空元素执行该函数。 6.

它的语法是-:

array.find(函数(值,索引,数组),thisValue)

它的语法是-:

array.filter(函数(值,索引,数组),thisValue)

7. 如果未找到任何元素,此方法将返回未定义。 在 filter() 方法中,一个值作为此值传递给函数



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3